﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.RequestModels.SysOrder;
using Ekton_Manage_DTO.RequestModels.User;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_Framework.Redis;
using Ekton_Manage_DTO.RequestModels.Product;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Ekton_Manage_Mapper.EntityMappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Ekton_Manage_IBusiness;
using Ekton_Manage_DTO.RequestModels;
using Ekton_Manage_DTO.APIRequestModels.SysUser;

namespace Ekton_Manage_Business
{
    class APIOrderList : IApiSelectOrder
    {   
        private readonly IBaseRepository<particulars_order, int> _baseMaterialRepository;
        private readonly IBaseRepository<user_orderView, int> _baseuserOrderVIewRepository;
        private readonly SerializeParameter _serialize;
        public APIOrderList(SerializeParameter serialize,IBaseRepository<particulars_order, int> baseMaterialRepository, IBaseRepository<user_orderView, int> baseuserOrderVIewRepository)
        {       
            _serialize = serialize;
            _baseMaterialRepository = baseMaterialRepository;
            _baseuserOrderVIewRepository = baseuserOrderVIewRepository;


        }

        /// <summary>
        ///  查询全部订单
        /// </summary>
        /// 
        public async Task<Tuple<List<user_orderView>, int>> GetOrder(QueryDataParame query)
        {
            var orderInfo = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<user_orderView, bool>> expression = m => true;
            if (orderInfo.ContainsKey("user_id") && !string.IsNullOrEmpty(orderInfo["user_id"].ToString()))
            {
                expression = expression.ExpressionAnd(m => Convert.ToString(m.user_id).Contains(orderInfo["user_id"].ToString()));
            }
            if (orderInfo.ContainsKey("name") && !string.IsNullOrEmpty(orderInfo["name"].ToString()))
            {
                expression = expression.ExpressionAnd(m => Convert.ToString(m.name).Contains(orderInfo["name"].ToString()));
            }
            if (orderInfo.ContainsKey("order_id") && !string.IsNullOrEmpty(orderInfo["order_id"].ToString()))
            {
                expression = expression.ExpressionAnd(m => Convert.ToString(m.order_id).Contains(orderInfo["order_id"].ToString()));
            }
            if (orderInfo.ContainsKey("company") && !string.IsNullOrEmpty(orderInfo["company"].ToString()))
            {
                expression = expression.ExpressionAnd(m => Convert.ToString(m.company).Contains(orderInfo["company"].ToString()));
            }
            if (orderInfo.ContainsKey("state") && !string.IsNullOrEmpty(orderInfo["state"].ToString()))
            {
                expression = expression.ExpressionAnd(m => Convert.ToString(m.state).Contains(orderInfo["state"].ToString()));
            }
            if (orderInfo.ContainsKey("order_time") && !string.IsNullOrEmpty(orderInfo["order_time"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.order_time >= orderInfo["order_time"].ObjToDate() && m.create_op_date <= orderInfo["order_time"].ObjToDate().AddDays(1));
            }
            return await _baseuserOrderVIewRepository.QueryPageData(query, expression);

        }


        /// <summary>
        /// 提交需求订单  
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Message> PostOrderList(ApiDtoInsertUserOrder request)
        {
            string key = "";
            string[] yCode = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
            Random ran = new Random();
            int randKey = ran.Next(0, 99);
            //获取微秒 （ 底层 api ）
            double l = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
            string unix = Convert.ToString((System.DateTime.Now.Ticks - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks) / 1000);
            // key = yCode[DateTime.Now.Year - 2011] + Convert.ToString(DateTime.Now.Month, 16).ToUpper() + DateTime.Now.Day + (unix.Substring(unix.Length - 6)) + l.ToString().Substring(0, 5) + randKey.ToString().PadLeft(2, '0');
            var RandomOrderId = "ST" + Convert.ToString(DateTime.Now.Month, 16).ToUpper() + DateTime.Now.Day + (unix.Substring(unix.Length - 6)) + l.ToString().Substring(0, 5) + randKey.ToString().PadLeft(2, '0');

            var orderId = RandomOrderId;
            //详情订单数据
            var particularsOorder = new particulars_order
            {
                product_name = request.product_name,
                product_describe = request.product_describe,
                product_picture = request.product_picture,
                materials_name = request.materials_name,
                color = request.color,
                design_name = request.design_name,
                // -- 状态    // 下单 ，出库 ...
                state = request.state,
                // 获取当前时间
                order_time = DateTime.Now,
                consignee_name = request.consignee_name,
                consignee_phone = request.consignee_phone,
                consignee_site = request.consignee_site,
                atient_id = request.atient_id,
                remark = request.remark,
                // 订单id
                order_id = orderId,
                // 用户id
                user_id = request.user_id,
                //选择牙齿id
                tooth_bits = request.tooth_bits,
                design = request.design,
                class_name = request.class_name,
                //上传文件附件
                file_upload =request.file_upload
            };
            var materials = await _baseMaterialRepository.InsertSingleData(particularsOorder);
            return new Message(orderId);
        }


        /// <summary>
        /// 修改备注
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Message> PutRemark(ApiDtoUpdateRemark request)
        {
            var companys = await _baseMaterialRepository.QuerySingleData(m => m.order_id == request.order_id);
            if (companys == null) return new Message(false, 202);
            companys.remark = request.remark;

            var result = await _baseMaterialRepository.UpdateSingleData(companys);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<Message> GetParticularsOrder(string order_id)
        {

            var result = await _baseMaterialRepository.QuerySingleData(m => m.order_id == order_id);
            return new Message(result);
        }



    }
}
